package com.bobi.tfca.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.databinding.ItemMemberRmLayoutBinding
import com.bobi.tfca.network.response.MemberResponse
import com.bobi.tfca.ui.mainnavigation.home.activity.ManageActMemberFragment
import com.bumptech.glide.Glide

class ActivityMemberAdapter(
    val fragment: ManageActMemberFragment,
    var memberResponseList: ArrayList<MemberResponse>
) :
    RecyclerView.Adapter<ActivityMemberAdapter.MemberViewHolder>(){

    private var checkedMemberList: ArrayList<Int> = ArrayList()
    var isOrganizer = false

    fun getCheckedMemberList(): ArrayList<Int> {
        return checkedMemberList
    }

    fun setCheckedMemberList(list: ArrayList<Int>) {
        this.checkedMemberList = list
    }

    inner class MemberViewHolder(private val binding: ItemMemberRmLayoutBinding) : RecyclerView.ViewHolder(binding.root)  {

        fun bind(position: Int) {
            val member = memberResponseList[position]
            binding.member = member
            val url = member.picture
            if (url != null && url.isNotBlank() && (!"null".equals(url))) {
                Glide.with(fragment).load(url).placeholder(R.drawable.default_avatar)
                    .into(binding.memberHead)
            }
            if (isOrganizer) {
                binding.cbMember.isChecked = false
                binding.cbMember.visibility = View.VISIBLE
                binding.cbMember.setOnCheckedChangeListener { compoundButton, b ->
                    val memberId = member.memberId
                    // 如果选中，则添加id
                    if (b) {
                        checkedMemberList.add(memberId)
                    } else {
                        // 取消选中，移除id
                        checkedMemberList.remove(memberId)
                    }
                }
            } else {
                binding.cbMember.visibility = View.GONE
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MemberViewHolder {
        val itemView = ItemMemberRmLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        val viewHolder = MemberViewHolder(itemView)
        return viewHolder
    }

    override fun getItemCount(): Int = memberResponseList.size

    override fun onBindViewHolder(holder: MemberViewHolder, position: Int) {
        with(holder) {
            bind(position)
        }
    }
}